//
//  FeedbackVM.swift
//  WatermarkCamera
//
//  Created by 赵新 on 8/7/2024.
//


import Foundation
import KeychainAccess

// MARK: - [FeedbackVM]

class FeedbackVM: NSObject {
    // Internal

    /// 路径
    var path: Html5Path?
    /// 参数
    var parameters: [String: String]?
    /// 问题类型
    var questionType: QuestionType?

    /// 构建 request
    /// - Parameter questionType: 问题类型
    /// - Returns: request对象
    func requestBuilder(questionType: QuestionType = .None) -> URLRequest {
        let url = self.getURLString()
        var param = [String: String]()
        // 有参数使用外部参数，没有使用默认的
        if let parameters = parameters {
            param = parameters
        } else {
            param = self.createDefaultParameters(questionType: questionType)
        }
        // 处理参数
        var urlComponents = URLComponents(string: url)
        var queryItems = [URLQueryItem]()
        for (key, value) in param {
            queryItems.append(URLQueryItem(name: key, value: value))
        }
        queryItems.append(URLQueryItem(name: "headers", value: self.createDefaultHeaders().jsonStringRepresentaiton))
        urlComponents?.queryItems = queryItems
        let request = URLRequest(url: (urlComponents?.url)!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
        return request
    }

    // Private

    /// 获取url
    /// - Returns: url stirng
    private func getURLString() -> String {
        let baseUrl = "https://h5hybridprod.yupaowang.com"
        let url = baseUrl + (self.path?.rawValue ?? "")
        return url
    }

    /// 创建默认 query参数
    /// - Parameter questionType: 默认问题类型
    /// - Returns: query参数
    private func createDefaultParameters(questionType: QuestionType = .None) -> [String: String] {
        var params: [String: String] = [:]
        // ids
        params["configId"] = "1"
        params["entryId"] = "2"
        params["appId"] = "101"
        // 来源
        params["resource"] = "gcdkxj_ios"
        params["tenatId"] = "5406"
        // 问题类型
        params["classificationId"] = questionType.rawValue
        // 安全区域高度
        params["top"] = "\(Int(SafeAreaTop))"
        params["bottom"] = "\(Int(SafeAreaBottom))"
        params["session"] = ""
        params["uid"] = "5406"
        return params
    }

    /// 创建默认header参数
    /// - Returns: header 参数
    private func createDefaultHeaders() -> [String: String] {
        var headers: [String: String] = [:]
        headers["source"] = "gcdkxj_ios"
        headers["packagename"] = Bundle.main.bundleIdentifier ?? ""
        headers["business"] = "SYXJ"
        headers["channel"] = "apple store"
        let jv = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "Unknown"
        headers["packageversion"] = jv
        headers["deviceId"] = Self.uuid
        headers["appVersion"] = jv
        return headers
    }
    static var uuid: String = {
        let key = "uuid"
        guard let info = Bundle.main.infoDictionary else { return "" }
        guard let identifier = info["CFBundleIdentifier"] as? String else { return "" }

        let keychain = Keychain(service: identifier)
        guard let uuid = keychain[key] else {
            let uuid: String? = UIDevice.current.identifierForVendor?.uuidString
            keychain[key] = uuid
            return uuid ?? "无UUID"
        }
        return uuid
    }()
}

extension FeedbackVM {
    /// 问题类型（水印相机反馈问题类型）
    enum QuestionType: String {
        case WatermarkType = "水印问题"
        case LocatingType = "定位问题"
        case None = ""
    }

    /// html5 页面 path(路径)
    enum Html5Path: String {
        // 意见反馈
        case feedback = "/feedback/add"

        var title: String {
            switch self {
            case .feedback:
                return "意见反馈"
            }
        }
    }
}

extension Dictionary {
    var jsonStringRepresentaiton: String? {
        guard let theJSONData = try? JSONSerialization.data(withJSONObject: self,
                                                            options: [.prettyPrinted]) else {
            return nil
        }

        return String(data: theJSONData, encoding: .ascii)
    }
}
